import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { RegionEntity } from '@entity/system/region.entity';
import { ListRegionDTO, CreateRegionDTO, UpdateRegionDTO } from '@dto/system/region.dto';
import { resBuild } from '@utils/resBuild';
import { checkKeyIsExist } from '@utils/serviceHelp';
import { getOperator } from '@utils';
import { HttpService } from '@midwayjs/axios';

@Provide()
export class RegionService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(RegionEntity)
  regionEntity: Repository<RegionEntity>;

  @Inject()
  httpService: HttpService;

  // 列表
  async list(queryParams: ListRegionDTO) {
    const qb = this.regionEntity.createQueryBuilder('entity');
    if (queryParams.regionName) {
      qb.andWhere(`entity.regionName like :name`, { name: `%${queryParams.regionName}%` });
    }
    if (queryParams.regionCode) {
      qb.andWhere(`entity.regionCode like :code`, { code: `%${queryParams.regionCode}%` });
    }
    if (queryParams.status) {
      qb.andWhere(`entity.status = :status`, { status: queryParams.status });
    }
    if (queryParams.pageNum && queryParams.pageSize) {
      qb.skip((queryParams.pageNum - 1) * queryParams.pageSize).take(queryParams.pageSize);
    }
    qb.addOrderBy('entity.orderNum', 'ASC').addOrderBy('entity.createTime', 'DESC');
    const [rows, total] = await qb.getManyAndCount();
    return resBuild.list(rows, total);
  }

  // 新增
  async create(body: CreateRegionDTO) {
    await checkKeyIsExist(this.regionEntity, 'regionCode', body.regionCode);
    const model = this.regionEntity.create(body as any) as unknown as RegionEntity;
    model.setCreateBy(getOperator(this.ctx));
    await this.regionEntity.save(model);
    return resBuild.success();
  }

  // 删除
  async delete(regionId: string) {
    const ids = regionId.split(',').map(id => Number(id));
    await this.regionEntity.delete(ids);
    return resBuild.success();
  }

  // 修改
  async update(body: UpdateRegionDTO) {
    const model = this.regionEntity.create(body as any) as unknown as RegionEntity;
    model.setUpdateBy(getOperator(this.ctx));
    await this.regionEntity.save(model);
    return resBuild.success();
  }

  // 详情
  async detail(regionId: number) {
    const data = await this.regionEntity.findOneBy({ regionId });
    return resBuild.data(data);
  }

  // 外部接口：新增区域
  async createExternal(payload: { regionCode: string; regionName: string; parentId?: number; orderNum?: number; status?: string; }) {
    const url = 'https://cmyd.jiwusiwei.com/inre/index.php/core/doi/save/bsqy?sign=c7d46abc31856f0472a7fe9e09eaa085';
    const form = new URLSearchParams();
    form.append('rid', '0');
    form.append('bh', payload.regionCode);
    form.append('mc', payload.regionName);
    form.append('fid', String(payload.parentId ?? 0));
    form.append('px', String(payload.orderNum ?? 1000));
    form.append('zt', String(payload.status ?? '1'));

    const resp = await this.httpService.post(url, form.toString(), {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
    return resp.data;
  }
}









